# -*- coding: utf-8 -*-
import FPLib
import os
import importlib
import traceback
import asyncio


from .FPAPIAPI import API
from .FPAPIPage import Page


class FPAPIHandler(object):
    """FPAPIHandler."""

    hashList = {}

    def __init__(self):
        super().__init__()

        self.re = ""
        self.path = ""
        self.type = "api"

    def init(self, api, server, req, *data, **kwargs):
        return True

    def set(self, re, path, type="api", init=None):

        self.re = re
        self.path = path
        self.init = init
        self.type = type

    def loadHash(self, hash):
        listHash = self.path + hash

        try:
            if not FPLib.conf.isdebug:
                if listHash in self.hashList:
                    # print("find")
                    return self.hashList.get(listHash)
            module = FPLib.ModuleLoader.loadByHash(hash, self.path, self.type)

            if module:
                self.hashList[listHash] = module
                return self.hashList[listHash]

        except Exception as e:
            # print("error", e)
            FPLib.findError(e)

        return self.call_404

    def handler(self, server, req, *data, **kwargs):
        try:
            asyncio.set_event_loop(asyncio.new_event_loop())

            if self.type == "api":
                handler = API(server)
            elif self.type == "page":
                handler = Page(server)
            else:
                return

            hash = False
            if len(server.path_args) == 1:
                hash = server.path_args[0]

            if hash:
                hash = hash.strip()
                if hash[-1] == "/":
                    hash = hash + "index"

                _run = True
                if self.init:
                    if self.init(handler, server, req, *data, **kwargs):
                        _run = False

                if _run:
                    callFunction = self.loadHash(hash)
                    return callFunction(handler, server, req, *data, **kwargs)
                    # _res = yield callFunction(handler, server, req, *data, **kwargs)
                    # return _res
        except Exception as e:
            print("Runtime Error:", hash, '-', e)
            FPLib.findError(e)
            # self.Error(e)
        pass

    def call_404(self, handler, server, req, *data, **kwargs):
        handler.call_404()
